<template>
  <div class="chart-container">
    <div class="chart-header">
      <h3>用户行为转化漏斗分析</h3>
    </div>
    <div ref="chart" style="width: 100%; height: 500px;"></div>
    
    <div class="conversion-table">
      <h4>转化率统计</h4>
      <table>
        <thead>
          <tr>
            <th>转化阶段</th>
            <th>用户数量</th>
            <th>转化率</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="conversionStats.length === 0">
            <td colspan="3" style="text-align:center; padding:20px; color:#999;">
              暂无转化数据
            </td>
          </tr>
          <tr v-else v-for="(item, index) in conversionStats" :key="index">
            <td>{{ item.stage }}</td>
            <td>{{ item.count }}</td>
            <td :class="getRateClass(item.rate)">
              {{ item.rate }}%
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { onMounted, ref, watch, onUnmounted, computed } from 'vue';

export default {
  name: 'ConversionFunnel',
  props: {
    chartData: {
      type: Array,
      default: () => []
    }
  },
  setup(props) {
    const chart = ref(null);
    let myChart = null;

    // 处理转化漏斗数据
    const funnelData = computed(() => {
      console.log('处理转化漏斗数据');
      
      // 新数据结构处理
      const stageMap = {};
      props.chartData.forEach(item => {
        if (item.name && item.value !== undefined) {
          stageMap[item.name] = {
            value: item.value,
            rate: item.rate
          };
        }
      });
      
      // 按照正确的转化顺序排列：浏览数 -> 加购数 -> 购买数
      const funnelStages = [];
      
      // 浏览数
      if (stageMap['浏览数']) {
        funnelStages.push({
          name: '浏览量(PV)',
          value: stageMap['浏览数'].value,
          rate: stageMap['浏览数'].rate
        });
      }
      
      // 加购数
      if (stageMap['加购数']) {
        funnelStages.push({
          name: '加购量',
          value: stageMap['加购数'].value,
          rate: stageMap['加购数'].rate
        });
      }
      
      // 购买数
      if (stageMap['购买数']) {
        funnelStages.push({
          name: '购买量',
          value: stageMap['购买数'].value,
          rate: stageMap['购买数'].rate
        });
      }
      
      console.log('转化漏斗数据:', funnelStages);
      return funnelStages;
    });

    // 计算转化率统计
    const conversionStats = computed(() => {
      const data = funnelData.value;
      if (data.length < 2) return [];
      
      const stats = [];
      
      // 浏览->加购转化率
      if (data.length >= 2 && data[0].value > 0) {
        const rate = ((data[1].value / data[0].value) * 100).toFixed(2);
        stats.push({
          stage: '浏览 → 加购',
          count: `${data[1].value} / ${data[0].value}`,
          rate: rate
        });
      }
      
      // 加购->购买转化率
      if (data.length >= 3 && data[1].value > 0) {
        const rate = ((data[2].value / data[1].value) * 100).toFixed(2);
        stats.push({
          stage: '加购 → 购买',
          count: `${data[2].value} / ${data[1].value}`,
          rate: rate
        });
      }
      
      // 浏览->购买转化率（总体转化率）
      if (data.length >= 3 && data[0].value > 0) {
        const rate = ((data[2].value / data[0].value) * 100).toFixed(2);
        stats.push({
          stage: '浏览 → 购买',
          count: `${data[2].value} / ${data[0].value}`,
          rate: rate
        });
      }
      
      return stats;
    });

    // 根据转化率获取样式类
    const getRateClass = (rate) => {
      const numRate = parseFloat(rate);
      if (numRate >= 10) return 'high-rate';
      if (numRate >= 5) return 'medium-rate';
      return 'low-rate';
    };

    // 初始化图表
    const initChart = () => {
      console.log('初始化转化漏斗图表');
      
      if (!chart.value) {
        console.error('图表容器未找到');
        return;
      }
      
      // 销毁旧的图表实例
      if (myChart) {
        myChart.dispose();
      }
      
      myChart = echarts.init(chart.value);
      const data = funnelData.value;
      
      // 无数据时显示提示
      if (data.length === 0 || data.every(item => item.value === 0)) {
        myChart.setOption({
          title: {
            text: '暂无转化数据',
            left: 'center',
            top: 'center',
            textStyle: {
              color: '#999',
              fontSize: 16
            }
          }
        });
        return;
      }
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            const dataIndex = params.dataIndex;
            const stage = data[dataIndex];
            return `
              <div style="font-weight: bold; margin-bottom: 5px;">${params.name}</div>
              <div>用户数量: ${stage.value.toLocaleString()}人</div>
              <div>阶段转化率: ${stage.rate}%</div>
              <div>占比: ${params.percent}%</div>
            `;
          }
        },
        legend: {
          data: data.map(item => item.name),
          bottom: 10,
          selectedMode: false, // 禁止点击图例切换显示
          inactiveColor: '#ccc', // 非激活状态颜色
          textStyle: {
            fontSize: 12
          }
        },
        series: [
          {
            name: '用户行为转化',
            type: 'funnel',
            left: '10%',
            top: 10,
            bottom: 100,
            width: '80%',
            min: 0,
            max: data[0].value, // 以浏览量为最大值
            minSize: '0%',
            maxSize: '100%',
            sort: 'descending', // 倒序排列
            gap: 2,
            label: {
              show: false, // 关闭内部标签显示
            },
            labelLine: {
              show: false // 关闭标签引导线
            },
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 1
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            data: data.map((item, index) => {
              const colors = ['#5470c6', '#91cc75', '#ee6666']; // 3个阶段的颜色
              return {
                name: item.name,
                value: item.value,
                itemStyle: {
                  color: colors[index] || '#73c0de'
                }
              };
            })
          }
        ]
      };
      
      myChart.setOption(option);
      
      // 添加鼠标事件监听，实现悬浮时高亮对应图例
      myChart.on('mouseover', function(params) {
        // 高亮对应的图例
        myChart.dispatchAction({
          type: 'highlight',
          name: params.name
        });
      });
      
      myChart.on('mouseout', function(params) {
        // 取消高亮
        myChart.dispatchAction({
          type: 'downplay',
          name: params.name
        });
      });
      
      console.log('转化漏斗图表配置已设置');
    };

    // 窗口缩放处理
    const handleResize = () => {
      if (myChart) {
        myChart.resize();
      }
    };

    // 组件挂载
    onMounted(() => {
      console.log('转化漏斗组件挂载完成');
      window.addEventListener('resize', handleResize);
      setTimeout(() => {
        initChart();
      }, 100);
    });

    // 组件卸载
    onUnmounted(() => {
      window.removeEventListener('resize', handleResize);
      if (myChart) {
        myChart.dispose();
      }
    });

    // 监听数据变化
    watch(() => props.chartData, () => {
      console.log('数据变化，重新渲染转化漏斗图表');
      if (myChart) {
        setTimeout(() => {
          initChart();
        }, 50);
      }
    }, { deep: true });

    
    return {
      chart,
      conversionStats,
      getRateClass
    };
  }
}
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  margin: 20px 0;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}
.chart-header h3 {
  margin: 0;
  color: #333;
}
.conversion-table {
  margin-top: 10px;
  height: 250px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  overflow: auto;
  box-sizing: border-box;
}

.conversion-table table {
  width: 100%;
  min-width: 400px;
  border-collapse: collapse;
  font-size: 14px;
}
.conversion-table h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #333;
  text-align: center;
}

.conversion-table th,
.conversion-table td {
  padding: 5px;
  text-align: center;
  border: 1px solid #eaeaea;
}
.conversion-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}
.conversion-table tr:hover {
  background-color: #f5f7fa;
}

.high-rate {
  color: #52c41a;
  font-weight: bold;
}
.medium-rate {
  color: #faad14;
  font-weight: bold;
}
.low-rate {
  color: #f5222d;
  font-weight: bold;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  .conversion-table {
    overflow-x: auto;
  }
  .conversion-table table {
    font-size: 12px;
  }
}
</style>